﻿Imports ComponentFactory.Krypton.Toolkit

Public Class DigitRestrictor

    Private ct As CharType
    Private chars() As Char

    Public Enum CharType
        Alphanumeric = 0
        Numeric = 1
        CharactersOnly = 2
    End Enum

    Public Property PermitedChars() As Char()
        Get
            Return (chars)
        End Get
        Set(ByVal value As Char())
            chars = value
        End Set
    End Property

    Public Property DefaultCharType() As CharType
        Get
            Return (ct)
        End Get
        Set(ByVal value As CharType)
            ct = value
        End Set
    End Property

    Sub New()
    End Sub

    Public Sub add(ByVal txt As TextBox)
        AddHandler txt.KeyPress, AddressOf eventHandler
    End Sub

    Public Sub add(ByVal txt As MaskedTextBox)
        AddHandler txt.KeyPress, AddressOf eventHandler
    End Sub

    Public Sub add(ByVal txt As KryptonMaskedTextBox)
        AddHandler txt.KeyPress, AddressOf eventHandler
    End Sub

    Public Sub add(ByVal txt As KryptonTextBox)
        AddHandler txt.KeyPress, AddressOf eventHandler
    End Sub

    Public Sub remove(ByVal txt As TextBox)
        RemoveHandler txt.KeyPress, AddressOf eventHandler
    End Sub

    Public Sub remove(ByVal txt As MaskedTextBox)
        RemoveHandler txt.KeyPress, AddressOf eventHandler
    End Sub

    Private Sub eventHandler(ByVal sender As Object, ByVal e As KeyPressEventArgs)

        Select Case (ct)
            Case CharType.Numeric
                If Not (Char.IsDigit(e.KeyChar)) And Not (e.KeyChar = ChrW(Keys.Back)) Then
                    If Not (verifyChar(e.KeyChar)) Then
                        e.KeyChar = DirectCast(Nothing, Char)
                    End If
                End If

            Case CharType.CharactersOnly
                If Not (Char.IsLetter(e.KeyChar)) And Not (e.KeyChar = ChrW(Keys.Back)) Then
                    If Not (verifyChar(e.KeyChar)) Then
                        e.KeyChar = DirectCast(Nothing, Char)
                    End If
                End If

            Case CharType.Alphanumeric
                If Not (Char.IsLetter(e.KeyChar)) And Not (Char.IsDigit(e.KeyChar)) And Not (e.KeyChar = ChrW(Keys.Back)) Then
                    If Not (verifyChar(e.KeyChar)) Then
                        e.KeyChar = DirectCast(Nothing, Char)
                    End If
                End If
        End Select

    End Sub

    Private Function verifyChar(ByRef c As Char) As Boolean
        If (chars IsNot Nothing) Then
            For i = 0 To chars.Length - 1
                If (c.Equals(chars(i))) Then
                    Return (True)
                ElseIf (i = chars.Length - 1 And Not c.Equals(chars(i))) Then
                    Return (False)
                End If
            Next
        End If
    End Function

End Class